package com.hcinfos.gsoo.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chatuidemo.activity.ChatActivity;
import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.HaveOrderAdapter;
import com.hcinfos.gsoo.adapter.MenuAdapter;
import com.hcinfos.gsoo.adapter.MenuDetailAdapter;
import com.hcinfos.gsoo.adapter.MenuScrollViewAdapter;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.GdDingzuoConfig;
import com.hcinfos.gsoo.enity.GdMealsDish;
import com.hcinfos.gsoo.enity.GdSupplerBasicConfExt;
import com.hcinfos.gsoo.enity.GdTakeAwayBasicConf;
import com.hcinfos.gsoo.enity.User;
import com.hcinfos.gsoo.enity.WType;
import com.hcinfos.gsoo.interfaze.DataCallback;
import com.hcinfos.gsoo.util.CommonUtil;
import com.hcinfos.gsoo.util.DateUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * 菜单 菜页面
 * 
 * @author xi
 * 
 */
public class MenuActivity extends Activity implements OnClickListener,
		DataCallback, OnPageChangeListener {

	private ListView menu_listView;
	private ListView menuDetail_listView;
	private MenuAdapter menuAdapter;
	private MenuDetailAdapter menuDetailAdapter, searchAdapter;

	private ImageView up_iv;
	private RelativeLayout scroll_rl;
	private ImageView left_arrow_iv;
	private ImageView right_arrow_iv;
	private ViewPager viewPager;
	private MenuScrollViewAdapter pagerAdapter;
	private TextView order_tv;
	private TextView disable_tv;
	private TextView total_num_tv;
	private TextView total_price_tv;
	private TextView centerName_tv;
	private TextView notif_tv;
	private ImageView home_iv;
	private Intent intent;
	private ImageView im_iv;

	private RelativeLayout had_order_rl;
	private ListView hadListView;// 已点菜单ListView
	private ImageView arrow_iv;
	private HttpUtils httpUitls;
	private RequestParams params;

	private ObjectMapper objectMapper;
	private List<GdMealsDish> detailList;

	public final int GET_TYPE_SUCCESS = 0x2210;
	public final int GET_TYPE_FAIL = GET_TYPE_SUCCESS + 1;
	public final int GET_CONFIG_SUCCESS = GET_TYPE_SUCCESS + 2;
	public final int GET_CONFIG_FAIL = GET_TYPE_SUCCESS + 3;
	public final int GET_DZ_CONFIG_SUCCESS = GET_TYPE_SUCCESS + 4;
	public final int GET_DZ_CONFIG_FAIL = GET_TYPE_SUCCESS + 5;

	private ProgressBar progress_bar;
	private FrameLayout content_fl;
	private ImageView error_img;
	private GdTakeAwayBasicConf basicConf;
	private HaveOrderAdapter orderAdapter;
	private List<GdMealsDish> orderList;

	private GdSupplerBasicConfExt detailExt;
	private ImageView back_iv;
	private RelativeLayout arrow_rl;
	private int selectPosition = -1;

	private EditText search_et;
	private TextView search_tv;
	private RelativeLayout search_rl;
	private RelativeLayout search_icon_rl;
	private ListView search_listView;
	private List<GdMealsDish> searchList;
	private List<GdMealsDish> allResultList;

	private ImageView close_iv;
	private RelativeLayout notif_rl;
	private int type = 0;
	private SharePreferenceUtil util;
	private User user;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_menu);
		allResultList = new ArrayList<GdMealsDish>();
		typesList = new ArrayList<WType>();
		searchList = new ArrayList<GdMealsDish>();
		detailList = new ArrayList<GdMealsDish>();
		objectMapper = new ObjectMapper();
		detailExt = (GdSupplerBasicConfExt) getIntent().getSerializableExtra(
				"detail");
		util = new SharePreferenceUtil(this, "setting");
		user = (User) util.loadObject("user");
		type = getIntent().getIntExtra("type", 0);
		initRes();
		refreshViews();
		if (detailExt != null) {
			centerName_tv.setText(detailExt.getSuppName());
			shopId = detailExt.getId();
			if (detailExt.getSouNo() == null) {
				im_iv.setVisibility(View.GONE);
			}

			LogUtil.d("wxf", "shopId=" + shopId);
		}

		obtainType();

		if (type == 0) {
			obtainDingzuoConfig();
		} else {
			obtainConfig();

		}
	}

	OnTouchListener touchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (had_order_rl.getVisibility() == View.VISIBLE) {
				had_order_rl.setVisibility(View.GONE);
			}
			return true;

		}
	};

	private void initRes() {

		im_iv = (ImageView) findViewById(R.id.im_iv);
		im_iv.setOnClickListener(this);
		notif_rl = (RelativeLayout) findViewById(R.id.notif_rl);
		close_iv = (ImageView) findViewById(R.id.close_iv);
		close_iv.setOnClickListener(this);
		searchAdapter = new MenuDetailAdapter(this, searchList);
		search_listView = (ListView) findViewById(R.id.search_listView);
		search_listView.setAdapter(searchAdapter);
		search_icon_rl = (RelativeLayout) findViewById(R.id.search_icon_rl);
		search_icon_rl.setOnClickListener(this);
		search_rl = (RelativeLayout) findViewById(R.id.search_rl);
		search_et = (EditText) findViewById(R.id.search_et);
		search_et.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

				if (s.length() > 0) {
					for (GdMealsDish dish : allResultList) {
						if (dish.getDishName().contains(s.toString())) {
							searchList.add(dish);
						}
					}
				} else {
					searchList.clear();
				}
				searchAdapter.setDataChange(searchList);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		search_tv = (TextView) findViewById(R.id.search_tv);
		search_tv.setOnClickListener(this);
		right_arrow_iv = (ImageView) findViewById(R.id.right_arrow_iv);
		right_arrow_iv.setOnClickListener(this);
		arrow_rl = (RelativeLayout) findViewById(R.id.arrow_rl);
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);
		home_iv = (ImageView) findViewById(R.id.home_iv);
		home_iv.setOnClickListener(this);
		home_iv.setVisibility(View.GONE);
		notif_tv = (TextView) findViewById(R.id.notif_tv);
		centerName_tv = (TextView) findViewById(R.id.centerName_tv);
		total_num_tv = (TextView) findViewById(R.id.total_num_tv);
		total_price_tv = (TextView) findViewById(R.id.total_price_tv);
		disable_tv = (TextView) findViewById(R.id.disable_tv);
		error_img = (ImageView) findViewById(R.id.error_img);
		content_fl = (FrameLayout) findViewById(R.id.content_fl);
		progress_bar = (ProgressBar) findViewById(R.id.progress_bar);
		order_tv = (TextView) findViewById(R.id.order_tv);
		order_tv.setOnClickListener(this);
		menu_listView = (ListView) findViewById(R.id.menu_listView);
		menuDetail_listView = (ListView) findViewById(R.id.menuDetail_listView);

		// scroll_rl.setVisibility(View.VISIBLE);
		menuAdapter = new MenuAdapter(this, typesList);
		menuDetailAdapter = new MenuDetailAdapter(this, detailList);
		menuDetailAdapter.setDataCallback(this);
		menu_listView.setAdapter(menuAdapter);
		menu_listView.setOnItemClickListener(menuItemOnClickListener);
		menuDetail_listView.setAdapter(menuDetailAdapter);
		menuDetail_listView
				.setOnItemClickListener(menuDetailItemOnClickListener);

		scroll_rl = (RelativeLayout) findViewById(R.id.scroll_rl);
		scroll_rl.setBackgroundColor(Color.argb(200, 0, 0, 0));
		scroll_rl.setOnClickListener(this);
		scroll_rl.setVisibility(View.GONE);
		left_arrow_iv = (ImageView) findViewById(R.id.left_arrow_iv);
		left_arrow_iv.setOnClickListener(this);

		viewPager = (ViewPager) findViewById(R.id.viewPager);
		pagerAdapter = new MenuScrollViewAdapter(detailList, this,
				new DataCallback() {

					@Override
					public void callback(int command) {
						scroll_rl.setVisibility(View.GONE);
					}
				});
		viewPager.setAdapter(pagerAdapter);

		had_order_rl = (RelativeLayout) findViewById(R.id.had_order_rl);
		hadListView = (ListView) findViewById(R.id.hadListView);
		arrow_iv = (ImageView) findViewById(R.id.arrow_iv);
		arrow_iv.setOnClickListener(this);
		had_order_rl.setOnClickListener(this);
		had_order_rl.setOnTouchListener(touchListener);

		orderList = new ArrayList<GdMealsDish>();
		orderAdapter = new HaveOrderAdapter(this, orderList);
		hadListView.setAdapter(orderAdapter);
		orderAdapter.setDataCallback(this);

		viewPager.setOnPageChangeListener(this);
		pagerAdapter.setDataCallback(this);
	}

	OnItemClickListener menuDetailItemOnClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {

			selectPosition = position;
			pagerAdapter.setDataChange(detailList);
			viewPager.setCurrentItem(selectPosition);
			scroll_rl.setVisibility(View.VISIBLE);
			if (detailList.size() == 1) {
				arrow_rl.setVisibility(View.GONE);
			} else {
				arrow_rl.setVisibility(View.VISIBLE);
			}
		}
	};

	OnItemClickListener menuItemOnClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {

			menuAdapter.setSelect(position);
			detailList = typesList.get(position).getList();
			pagerAdapter.setDataChange(detailList);
			menuDetailAdapter.setDataChange(typesList.get(position).getList());
		}
	};

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.scroll_rl:
			if (scroll_rl.getVisibility() == View.VISIBLE) {
				scroll_rl.setVisibility(View.GONE);
			}
			break;
		case R.id.left_arrow_iv:
			if (selectPosition == 0) {
				Toast.makeText(this, "已经是第一条数据", 500).show();
			} else {
				selectPosition -= 1;
				if (selectPosition <= 0)
					selectPosition = 0;
			}
			viewPager.setCurrentItem(selectPosition);

			break;
		case R.id.right_arrow_iv:
			if (selectPosition == detailList.size() - 1) {
				Toast.makeText(this, "已经是最后一条数据", 500).show();
			} else {
				selectPosition += 1;
				if (selectPosition >= detailList.size() - 1) {
					selectPosition = detailList.size() - 1;
				}
			}
			viewPager.setCurrentItem(selectPosition);
			break;
		case R.id.order_tv:
			double price = 0.0;
			if (type == 1) {
				intent = new Intent(this, WaimaiOrderConfirActivity.class);
				price = basicConf.getServicePrice();
			} else {
				intent = new Intent(this, DingzuoSubmitActivity.class);
				intent.putExtra("config", dingzuoConfig);
			}
			intent.putExtra("detailExt", detailExt);
			intent.putExtra("price", price);
			startActivity(intent);
			break;
		case R.id.arrow_iv:
			if (had_order_rl.getVisibility() == View.VISIBLE) {
				had_order_rl.setVisibility(View.GONE);
				menuDetailAdapter.notifyDataSetChanged();
			} else {
				refreshPullData();
				had_order_rl.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.home_iv:
			intent = new Intent(this, ShopDetailActivity.class);
			intent.putExtra("suppId", shopId);
			startActivity(intent);
			break;
		case R.id.back_iv:
			finish();
			break;
		case R.id.search_tv:
			search_rl.setVisibility(View.GONE);
			refreshPullData();
			break;
		case R.id.search_icon_rl:
			search_rl.setVisibility(View.VISIBLE);
			break;
		case R.id.close_iv:
			notif_rl.setVisibility(View.GONE);
			break;
		case R.id.im_iv:
			if (user == null) {
				Toast.makeText(this, "请先登录再操作！", 500).show();
				return;
			}
			if (detailExt != null) {
				Intent intent = new Intent(this, ChatActivity.class);
				intent.putExtra("userId", "X" + detailExt.getSouNo());
				startActivity(intent);
			}
			break;
		}
	}

	/**
	 * 根据gsoo号查找 用户名
	 */
	private void findNameByGsoo() {

		httpUitls = UtilHttp.getHttpUtils(this);
		params = new RequestParams();
		// params.addBodyParameter("user.ggnumber", file)
		httpUitls.send(HttpRequest.HttpMethod.POST, Urls.W_GET_TYPE, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {

						String result = responseInfo.result;
						LogUtil.d("wxf", "result=" + result);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", "result=" + error.toString());
					}

				});

	}

	/**
	 * 获取菜单数据
	 */
	private String shopId = "testsuppler";
	private List<WType> typesList;

	private void obtainType() {
		typesList.clear();
		detailList.clear();
		params = new RequestParams();
		params.addBodyParameter("beanProxy.suppId", shopId);
		httpUitls = new HttpUtils();
		httpUitls.send(HttpRequest.HttpMethod.POST, Urls.W_GET_TYPE, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						LogUtil.e("wxf",
								"arg1" + arg1 + "exception =" + arg0.toString());
					}

					@Override
					public void onSuccess(ResponseInfo<String> text) {
						LogUtil.d("wxf", "result=" + text.result);
						try {
							JSONObject obj = new JSONObject(text.result);
							int state = obj.getInt("state");
							String rows = obj.getString("rows");
							if (state == 200) {
								List<GdMealsDish> resultList = objectMapper
										.readValue(
												rows,
												new TypeReference<List<GdMealsDish>>() {
												});
								// detailList.addAll(resultList);
								LogUtil.d("wxf",
										"resultList=" + resultList.size());
								if (resultList != null) {
									List<GdMealsDish> types = new ArrayList<GdMealsDish>();
									types.addAll(resultList);
									HashSet<GdMealsDish> hs = new HashSet<GdMealsDish>(
											types);
									types.clear();
									types.addAll(hs);

									for (GdMealsDish typeDish : types) {
										WType wType = new WType();
										wType.setTypeName(typeDish
												.getTypeName());
										typesList.add(wType);
									}

									for (WType type : typesList) {
										List<GdMealsDish> list = new ArrayList<GdMealsDish>();
										for (GdMealsDish gd : resultList) {
											if (type.getTypeName().equals(
													gd.getTypeName())) {
												list.add(gd);
											}
										}
										type.setList(list);
									}

								}
								handler.sendEmptyMessage(GET_TYPE_SUCCESS);

							} else {
								handler.sendEmptyMessage(GET_TYPE_FAIL);
							}

						} catch (Exception e) {
							handler.sendEmptyMessage(GET_TYPE_FAIL);
							LogUtil.e("wxf", e.toString());
						}

					}

				});
	}

	/**
	 * 根据id获得外卖详情
	 */
	private void obtainConfig() {

		params = new RequestParams();
		params.addBodyParameter("record.id", shopId);
		params.addBodyParameter("prefix", "");
		httpUitls = new HttpUtils();
		httpUitls.send(HttpRequest.HttpMethod.POST, Urls.W_GET_CONFIG, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						LogUtil.e("wxf",
								"obtainConfig exception = " + arg0.toString());
					}

					@Override
					public void onSuccess(ResponseInfo<String> text) {
						LogUtil.d("wxf", "obtainConfig =" + text.result);
						try {
							basicConf = objectMapper.readValue(text.result,
									new TypeReference<GdTakeAwayBasicConf>() {
									});
							handler.sendEmptyMessage(GET_CONFIG_SUCCESS);

						} catch (Exception e) {
							handler.sendEmptyMessage(GET_CONFIG_FAIL);
							LogUtil.e("wxf", e.toString());
						}

					}
				});
	}

	private GdDingzuoConfig dingzuoConfig;

	/**
	 * 获取订座配置
	 */
	private void obtainDingzuoConfig() {
		httpUitls = UtilHttp.getHttpUtils(this);
		params = new RequestParams();
		params.addBodyParameter("record.id", shopId);
		params.addBodyParameter("prefix", "");
		httpUitls = new HttpUtils();
		httpUitls.send(HttpRequest.HttpMethod.POST, Urls.W_GET_DINGZUO_CONFIG,
				params, new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {

						String result = responseInfo.result;
						if (result != null) {

							try {
								dingzuoConfig = objectMapper.readValue(result,
										new TypeReference<GdDingzuoConfig>() {
										});
								handler.sendEmptyMessage(GET_DZ_CONFIG_SUCCESS);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						} else {

						}
						LogUtil.d("wxf", "result=" + result);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.d("wxf", "result=" + error);
					}
				});

	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case GET_TYPE_FAIL:
				error_img.setVisibility(View.VISIBLE);
				content_fl.setVisibility(View.GONE);
				progress_bar.setVisibility(View.GONE);
				break;
			case GET_TYPE_SUCCESS:
				error_img.setVisibility(View.GONE);
				progress_bar.setVisibility(View.GONE);
				content_fl.setVisibility(View.VISIBLE);
				menuAdapter.setDataChange(typesList);
				if (typesList.size() > 0) {
					menuDetailAdapter.setDataChange(typesList.get(0).getList());
					detailList = typesList.get(0).getList();
					pagerAdapter.setDataChange(detailList);
					for (WType type : typesList) {
						if (type.getList() != null && type.getList().size() > 0) {
							allResultList.addAll(type.getList());
						}
					}
				}

				break;
			case GET_CONFIG_SUCCESS:
				refreshViews();

				if (type == 1) {
					disable_tv.setText("还差" + basicConf.getSendPrice() + "元起送");
					notif_tv.setText(basicConf.getOrderNotice() == null ? "暂无"
							: basicConf.getOrderNotice());
					String startTime = detailExt.getTaStartTime();
					String endTime = detailExt.getTaEndTime();
					if (DateUtil.compare_date(startTime) > 0
							&& DateUtil.compare_date(endTime) < 0) {
					} else {
						order_tv.setVisibility(View.GONE);
						disable_tv.setVisibility(View.VISIBLE);
						disable_tv.setText("不可外卖");
					}
				}

				break;
			case GET_DZ_CONFIG_SUCCESS:
				refreshViews();
				disable_tv
						.setText("还差" + dingzuoConfig.getMinConsume() + "元预订");
				notif_tv.setText(dingzuoConfig.getTableOrderNotice() == null ? "暂无"
						: dingzuoConfig.getTableOrderNotice());
				break;
			case GET_DZ_CONFIG_FAIL:

				break;
			}
		};
	};

	@Override
	public void callback(int command) {
		refreshViews();
		refreshPullData();
	}

	@Override
	protected void onResume() {
		menuDetailAdapter.notifyDataSetChanged();
		// GsooApplication.menuMap.clear();
		total_num_tv.setText("共计" + 0 + "个菜");
		total_price_tv.setText("¥" + 0);
		refreshViews();
		super.onResume();
	}

	private void refreshViews() {
		try {
			int totalNum = 0;
			double totalPrice = 0.0;
			double price = 0.0;
			Map<String, GdMealsDish> orderMap = GsooApplication.menuMap;
			for (String key : orderMap.keySet()) {
				GdMealsDish extend = orderMap.get(key);
				totalNum += extend.getNum();
				price = extend.getDishPrice() * extend.getNum();
				totalPrice += price;
			}
			total_num_tv.setText("共计" + totalNum + "个菜");
			total_price_tv.setText("¥" + CommonUtil.round(totalPrice, 2));

			if (type == 0) {
				if (dingzuoConfig != null) {
					double sendPrice = dingzuoConfig.getMinConsume();
					if (totalPrice >= sendPrice) {
						order_tv.setVisibility(View.VISIBLE);
						disable_tv.setVisibility(View.GONE);
					} else {
						disable_tv.setVisibility(View.VISIBLE);
						order_tv.setVisibility(View.GONE);
						disable_tv.setText("还差" + (sendPrice - totalPrice)
								+ "元可预订");
					}
				} else {
					return;
				}
			} else {
				if (basicConf != null) {
					double sendPrice = basicConf.getSendPrice();
					if (totalPrice >= sendPrice) {
						order_tv.setVisibility(View.VISIBLE);
						disable_tv.setVisibility(View.GONE);
					} else {
						disable_tv.setVisibility(View.VISIBLE);
						order_tv.setVisibility(View.GONE);
						disable_tv.setText("还差" + (sendPrice - totalPrice)
								+ "元起送");

						String startTime = detailExt.getTaStartTime();
						String endTime = detailExt.getTaEndTime();
						if (DateUtil.compare_date(startTime) > 0
								&& DateUtil.compare_date(endTime) < 0) {
						} else {
							order_tv.setVisibility(View.GONE);
							disable_tv.setVisibility(View.VISIBLE);
							disable_tv.setText("不可外卖");
						}
					}

				} else {
					return;
				}

			}

		} catch (Exception e) {
			LogUtil.e("wxf", "refreshViews =" + e.toString());
		}
	}

	private void refreshPullData() {
		refreshViews();
		orderList.clear();
		Map<String, GdMealsDish> orderMap = GsooApplication.menuMap;
		for (String key : orderMap.keySet()) {
			orderList.add(orderMap.get(key));
		}
		orderAdapter.setDataChange(orderList);
		menuDetailAdapter.notifyDataSetChanged();
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int position) {

	}
}
